import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Main {
    public static void main(String[] args) {
        try {
            //创建服务器端的ServerSocket对象,等待客户端连接

            ServerSocket serverSocket=new ServerSocket(80, 20);

            //创建线程池,从而可以处理多个客户端
            ExecutorService executorService= Executors.newFixedThreadPool(100);


            //当前线程数量
            int threadCount = ((ThreadPoolExecutor)executorService).getActiveCount();

            while (threadCount <= ((ThreadPoolExecutor) executorService).getMaximumPoolSize()) {
                //线程满，进入循环
                while (threadCount == ((ThreadPoolExecutor) executorService).getMaximumPoolSize()){
                    //更新当前线程数量
                    threadCount = ((ThreadPoolExecutor)executorService).getActiveCount();
                }

                //监听客户端
                Socket socket=serverSocket.accept();

                //4.启动线程
                executorService.execute(new Server(socket));

                //获取IP输出
                InetAddress address=socket.getInetAddress();
                System.out.println("IP: "+address.getHostAddress());

                //更新当前线程数量
                threadCount = ((ThreadPoolExecutor)executorService).getActiveCount();
            }

            //关闭线程池
            executorService.shutdown();
            //关闭服务器
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}